package dao.impl;

import dao.PetOwnerDao;
import entity.Pet;
import entity.PetOwner;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class PetOwnerDaoImpl extends BaseDao implements PetOwnerDao {
    @Override
    public List<PetOwner> getPetOwnerList() throws Exception {
        connection = getConnection();
        String sql = "select * from petowner";
        resultSet = query(sql, null);
        ArrayList<PetOwner> list = new ArrayList<>();
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String password = resultSet.getString("password");
            int money = resultSet.getInt("money");

            PetOwner petOwner = new PetOwner();
            petOwner.setId(id);
            petOwner.setName(name);
            petOwner.setMoney(money);
            petOwner.setPassword(password);
            //添加到集合
            list.add(petOwner);
        }
        close(resultSet, statement, connection);
        return list;
    }

    @Override
    public int login(PetOwner petOwner) throws Exception {
        connection = getConnection();
        String sql = "select * from petowner where id=? and name=?";
        Object[] objects = new Object[2];
        objects[0] = petOwner.getId();
        objects[1] = petOwner.getName();
        int update = update(sql, objects);
        resultSet = query(sql, objects);
        while (resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String password = resultSet.getString("password");
            int money = resultSet.getInt("money");
            petOwner.setMoney(money);
            petOwner.setId(id);
            petOwner.setName(name);
            petOwner.setPassword(password);
        }



        close(resultSet, statement, connection);
        return update;
    }
//买
    @Override
    public int getBuy(Integer price, Integer id) throws Exception{
        connection=getConnection();
       String sql="update petowner set money=money-? where id=?";
        Object[] objects = {price,id};
        int update = update(sql, objects);
        close(resultSet,statement,connection);
        return update;
    }
//卖
    @Override
    public int changeOwner(Integer price, Integer id) throws Exception{
        connection=getConnection();
        String sql="update petowner set money=money+? where id=?";
        Object[] objects = {price,id};
        int update = update(sql, objects);
        close(resultSet,statement,connection);
        return update;
    }


}
